//
//  MessagePeopleViewController.m
//  jungoo
//
//  Created by Sinbad Flyce on 9/25/12.
//  Copyright (c) 2012 VMODEV. All rights reserved.
//

#import "MessagePeopleViewController.h"
#import "Extensions.h"

@implementation MessagePeopleViewController

@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];    
}

#pragma mark - Private

- (UITableViewCell*)createTopCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    
    return (id)[views objectAtIndex:5];
}

- (UISearchBar*)createSearchBarFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    UISearchBar *searchBar = (id)[views objectAtIndex:1];
    
    searchBar.delegate = self;
    
    return searchBar;
}
-(void)initTitleBar
{
    UIView *viewTitle = [[[UIView alloc] init] autorelease];
    viewTitle.backgroundColor = [UIColor clearColor];
    viewTitle.frame = CGRectMake(0, 0, 160, 30);
    
    NSArray *segmentTextContent = [NSArray arrayWithObjects: @"All", @"Favorites", nil];
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
    segmentedControl.frame = CGRectMake(0, 0, 160, 30);
    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segmentedControl setSelectedSegmentIndex:0];
	hasSetSelectedIndexOnce = NO;
    
    for( int i = 0; i < [[segmentedControl subviews]count]; i++ )
    {
        // reset color
        [[[segmentedControl subviews] objectAtIndex:i] setTintColor:nil];
        [[[segmentedControl subviews] objectAtIndex:i] setTintColor:[UIColor colorWithRed:120./255 green:120./255 blue:120./255 alpha:1]];
    }
    
    [[[segmentedControl subviews] objectAtIndex:0] setTintColor:[UIColor colorWithRed:20./255 green:178./255 blue:241./255 alpha:1]];
    [viewTitle addSubview:segmentedControl];

	[segmentedControl release];
    self.navigationItem.titleView = viewTitle;    
}
- (void)initAppearance
{    
    [self setBackButtonImageActiveName:@"" 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(done)];
    /*
    [self setRightButtonImageActiveName:@""
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done)];
     */
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Loading..."
                          selector:@selector(delayLoadPeople:)];
        
    [self initTitleBar];
}

- (void)asyncLoadAvatars
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        for (NSDictionary *aPerson in masterDataSource) {
            
            if ([aPerson isKindOfClass:[NSDictionary class]]) {
                
                NSString *senderAvatarURL = (id)[aPerson objectForKey:@"thumb"];
                NSString *senderId = [aPerson objectForKey:@"user_id"];
                
                if ([[JGoUtility sharedCachedAvatars] objectForKey:senderId] == nil) {
                    
                    UIImage *senderAvatar = [JGoAPI downloadAvatar:senderAvatarURL error:nil];
                    [[JGoUtility sharedCachedAvatars] setValue:senderAvatar forKey:senderId];
                    
                    if (senderAvatar != nil) {
                        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                    }
                }
            }
            
        }
        
    });    
}

#pragma mark - Action

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)done
{
    NSMutableArray *peopleSeleted = [[NSMutableArray new] autorelease];
    
    for (NSDictionary *aPerson in dataSource) {
        
        if ([[aPerson objectForKey:@"check"] integerValue] == 1) {
            
            [peopleSeleted addObject:aPerson];
        }
    }
    
    if ([self.delegate respondsToSelector:@selector(didSelectPeopleToJoinChat:)]) {
        
        if ([peopleSeleted count]) {
            
            [self.delegate didSelectPeopleToJoinChat:peopleSeleted];
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)segmentAction:(id)sender
{
	//NSLog(@"segmentAction: selected segment = %d", [sender selectedSegmentIndex]);
    int index = [sender selectedSegmentIndex];
    int numSegments = [[sender subviews] count];
    
    for( int i = 0; i < numSegments; i++ )
    {
        // reset color
        [[[sender subviews] objectAtIndex:i] setTintColor:nil];
        [[[sender subviews] objectAtIndex:i] setTintColor:[UIColor colorWithRed:120./255 green:120./255 blue:120./255 alpha:1]];
    }
    hasSetSelectedIndexOnce = YES;
    if( hasSetSelectedIndexOnce )
    {
        [[[sender subviews] objectAtIndex: numSegments - 1 - index] setTintColor:[UIColor colorWithRed:20./255 green:178./255 blue:241./255 alpha:1]];
    }
    if (index == 0) {
        [JGoUtility showProgressInView:self.view
                                target:self
                                 title:@"Loading..."
                              selector:@selector(delayLoadPeople:)];
    }else{
        [JGoUtility showProgressInView:self.view
                                target:self
                                 title:@"Loading..."
                              selector:@selector(delayLoadFavoritesPeople:)];
    }
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initAppearance];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - TableDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataSource count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;       
            
    [tableView dequeueReusableCellWithIdentifier:@"People-Cell"];
    
    if (cell == nil) {
        cell = [self createTopCellFromNib];
    }
    
    NSDictionary *aPerson = [dataSource objectAtIndex:indexPath.row];
    NSString *senderId = [aPerson objectForKey:@"user_id"];
    NSInteger check = [[aPerson objectForKey:@"check"] integerValue];
    
    [cell titleTextWithTag:2].text = [aPerson objectForKey:@"name"];
    [cell titleTextWithTag:3].text = [aPerson objectForKey:@"university"];
    [cell imageViewWithTag:1].image = [[JGoUtility sharedCachedAvatars] objectForKey:senderId];
    [[cell imageViewWithTag:1] makeBorderRound];
    [cell buttonWithTag:4].selected = check;        
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 76;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *aPerson = [dataSource objectAtIndex:indexPath.row];
    NSInteger check = [[aPerson objectForKey:@"check"] integerValue]; 
    check = !check;
    [aPerson setValue:[NSString stringWithFormat:@"%d",check] forKey:@"check"];
    
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];    
}

#pragma mark - Delay Method

- (void)delayLoadFavoritesPeople:(MBProgressHUD*)progress
{
    NSError *error = nil;
    NSString *lat = [JGoUtility sharedLatitude];
    NSString *lon = [JGoUtility sharedLongitude];
    
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSArray *pepople = nil;
    
    pepople = [JGoAPI getPeopleWithUserId:userId
                                 searchBy:@""
                                    isFav:YES
                                   filter: @""
                                      lat:lat
                                      lon:lon
                                    error:&error];
    if (error) {
        LOG(@"%@", [error localizedDescription]);
    }
    
    else {
        dataSource = (id)[pepople retain];
        masterDataSource = [dataSource mutableCopy];
        [self asyncLoadAvatars];
    }
    
    [self.tableView reloadData];
    [progress hide:YES];
}


- (void)delayLoadPeople:(MBProgressHUD*)progress
{
    NSError *error = nil;
    NSString *lat = [JGoUtility sharedLatitude];
    NSString *lon = [JGoUtility sharedLongitude];
    
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSArray *pepople = nil;
    
    pepople = [JGoAPI getPeopleWithUserId:userId
                                      searchBy:@""
                                         isFav:NO 
                                        filter: @""
                                           lat:lat
                                           lon:lon
                                         error:&error];
    if (error) {        
        LOG(@"%@", [error localizedDescription]);
    }
    
    else {
        dataSource = (id)[pepople retain];
        masterDataSource = [dataSource mutableCopy];
        [self asyncLoadAvatars];
    }
    
    [self.tableView reloadData];    
    [progress hide:YES];
}

#pragma mark - SearchBar Delegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [dataSource release];
    
    if ([searchText length]) {
        dataSource = [NSMutableArray new];
        
        for (NSDictionary *aPerson in masterDataSource) {
            
            NSString *curString = [aPerson objectForKey:@"name"];
            NSRange substringRange = [curString rangeOfString:searchText options:NSCaseInsensitiveSearch];
            
            if (substringRange.length != 0) {
                [dataSource addObject:aPerson];
            }
        }
    }
    else {
        dataSource = [masterDataSource mutableCopy];
    }
    
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

@end
